<template>
  <el-select
    v-loadmore="loadMore"
    v-model="selectData"
    :filter-method="filterData"
    :placeholder="placeholder"
    :disabled="disabled"
    :multiple="multiple"
    :no-data-text="emptyText"
    collapse-tags
    filterable
    popper-class="global-select-down"
    clearable
    size="small"
    class="user-select filterableSelect remoteRequest1 filter-select"
    @change="selectChange">
    <el-option
      v-for="item in filterSelects"
      :key="item[valueFiled]"
      :label="`${item[labelFiled]}`"
      :value="item[valueFiled]"/>
    <div v-if="isLoading" class="loading-container"><i class="el-icon-loading"/></div>
  </el-select>
</template>
<script>
import requestProxy from '@/utils/request';
const { request } = requestProxy;
export default {
  name: 'LoadMoreSelect',
  model: {
    prop: 'param',
    event: 'change'
  },
  props: {
    param: {
      type: Number | String,
      default: null
    },
    apiUrl: {
      type: String,
      default: ''
    },
    keyword: {
      type: String,
      default: ''
    },
    defaultParams: {
      type: Array,
      default: () => {
        return [];
      }
    },
    extendParams: {
      type: Object,
      default: () => ({})
    },
    valueFiled: {
      type: String,
      default: ''
    },
    labelFiled: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    isDefault: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    emptyText: {
      type: String,
      default: '无数据'
    },
    isImmediatelyQuery: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isLoading: false,
      selects: {
        items: [],
        total: '',
        page: 1,
        perPage: 20
      },
      selectedItems: [],
      searchName: ''
    };
  },
  computed: {
    selectData: {
      get() {
        return this.param;
      },
      set(val) {
        this.collectSelectedItems(val);
      }
    },
    filterSelects() {
      if (this.defaultParams.length > 0) {
        const temp = [...this.defaultParams];
        if (this.selects.items) {
          const defaults = this.defaultParams.map(item => item[this.valueFiled]);
          this.selects.items.forEach(item => {
            if (defaults.indexOf(item[this.valueFiled]) < 0) {
              temp.push(item);
            }
          });
        }
        return temp;
      }
      return this.selects.items;
    }
  },
  created() {
    this.isImmediatelyQuery && this.getSelectMethods(1, '');
  },
  methods: {
    selectChange(val) {
      this.collectSelectedItems(val);
    },
    collectSelectedItems(val) {
      let selectedItems = this.selectedItems;
      if (val && val instanceof Array) {
        val.forEach((i) => {
          const selected = this.selects.items.find((item) => i === item.id);
          selected && !selectedItems.find((item) => i === item.id) && selectedItems.push(selected);
        });
        this.selectedItems = selectedItems.filter(item => val.includes(item.id));
      } else {
        const selected = this.selects.items.find((item) => val === item.id);
        if (selected) selectedItems = selected;
      }
      this.$emit('getSelectedItem', { selectedItems }, val);
      this.$emit('change', val);
    },
    requestApi(page, perPage, params) {
      return request({
        url: `${this.apiUrl}`,
        method: 'get',
        params: {
          page,
          perPage,
          ...params
        }
      });
    },
    filterData: _.debounce(function(val) {
      this.$emit('loadMoreFilter', val);
      this.searchName = val;
      this.getSelectMethods(1, val);
    }, 200),
    loadMore() {
      const list = this.filterSelects;
      const selects = this.selects;
      const currentPage = selects.page;
      const isMax = list.length >= selects.total;
      if (!isMax && !this.isLoading) {
        this.getSelectMethods(currentPage + 1);
      }
    },
    getSelectMethods(page, name = '') {
      const params = {
        ...this.extendParams
      };
      // params[this.keyword] = name;
      params[this.keyword] = this.searchName;
      this.isLoading = true;
      this.requestApi(page, 10, params).then(res => {
        this.isLoading = false;
        if (res.code === 200) {
          if (page > 1 && this.selects.items) {
            const concatList = this.selects.items.concat(res.data.items);
            res.data.items = concatList;
            this.selects = res.data;
          } else {
            this.selects = res.data;
          }
        }
      }).catch((_) => {
        this.isLoading = false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
.remoteRequest1 {
  &::v-deep {
    @extend %custom-mul-select !optional;
    .el-select__tags>span {
      max-width: 110px;
    }
    .el-tag.el-tag--info:first-child {
      min-width: 50px;
      width: 52%;
    }
    .el-tag.el-tag--info:nth(2) {
      min-width: 38px;
    }
  }
}
.filter-select {
  &::v-deep {
    .el-tag > span {
      min-width: 20px !important;
      max-width: 40px !important;
    }
    .el-tag.el-tag--info:first-child {
      min-width: 20px !important;
      width: auto;
    }
    .el-tag.el-tag--info:last-child {
      padding-left: 1px;
      padding-right: 1px;
      margin-left: 4px;
    }
    .el-tag.el-tag--info .el-tag__close {
      right: -2px;
      top: 3px;
    }
    .el-tag.el-tag--info .el-tag__close:hover {
      background-color: #909399;
    }
  }
}
</style>
